<template>
	<view class="c">
		<u-sticky>
			<view style="background-color: #fff">
				<u-tabs
					:lineColor="`#fe0203`"
					:activeStyle="{
						color: '#fe0203',
						fontWeight: 'bold'
					}"
					:current="m_current"
					:list="m_list"
					@click="onTabClick"
				/>
			</view>
		</u-sticky>
		<u-transition :show="m_show" mode="slide-left">
			<view v-if="m_pageData.length > 0">
				<!-- orders -->
				<view class="gs" v-for="(order, _index) in m_pageData" :key="order.rowId">
					<view class="ct">
						<view class="t">
							<view class="lf">订单号:{{ order.number }}</view>

							<view class="rf">
								<text class="payname">{{ order.payname }}</text>
								<text class="StateName">({{ order.StateName }})</text>
							</view>
						</view>
						<view v-on:tap="onOrderClick(order)" class="product" v-for="(good, key) in order.data" :key="key">
							<image class="image" :src="imageUrl + good.img" mode="aspectFit" />
							<view class="content">
								<view class="name">{{ good.title }}</view>
							</view>
							<view class="p-c">
								<view class="p">￥{{ parseFloat(good.price).toFixed(2) }}</view>
								<view class="q">x{{ parseInt(good.qty) }}</view>
							</view>
						</view>
					</view>
					<!-- summary -->
					<view class="s">
						<view class="l"></view>
						<view class="r">
							<text class="qty">共{{ parseInt(order.qty) }}件，</text>
							<text class="r">实付:</text>
							<text class="sb">￥</text>
							<text class="total">{{ parseFloat(order.total).toFixed(2) }}</text>
						</view>
					</view>
					<!-- operations -->
					<view class="opt" v-if="order.StateId == 0">
						<view v-on:tap="onBtnClick(1, order)" class="btn">取消订单</view>
						<view v-on:tap="onBtnClick(2, order)" class="btn btn-pay">去付款</view>
					</view>
					<view class="opt" v-if="order.StateId == 2">
						<view v-on:tap="onBtnClick(3, order)" class="btn">确认收货</view>
					</view>
				</view>
			</view>
			<view v-else style="display: flex; flex-direction: column; align-items: center; justify-content: center; padding-top: 30px">
				<image src="/static/images/order/no-order.png" style="width: 300rpx" mode="widthFix" />
				<view style="color: #141414">暂无订单</view>
				<view style="color: #b39385; margin-top: 5px">偶尔又要犒劳一下自己哦</view>
				<view
					style="
						margin-top: 15px;
						padding: 10px 30px;
						color: #fff;
						width: 60px;
						background-color: #ff2a35;
						border-radius: 20px;
						display: flex;
						align-items: center;
						justify-content: center;
					"
					v-on:tap="goShopping"
				>
					去逛逛
				</view>
			</view>
		</u-transition>
	</view>
</template>

<script>
import { onMounted, reactive, ref } from '@vue/composition-api';
import { reqPost } from '../../common/http.request';
import { useUser } from '../../store/useUser';
import { uGetStorageSync, uModal, uNavigateBack, uNavigateTo, uRedirectTo, uSwitchTab, uToast } from '../../utils/uniUtils';

export default {
	onReachBottom() {
		console.log('onReachBottom');
		if (this.m_Total > this.m_pageData.length) {
			this.m_PageIndex += 1;
			this.GetOrderList();
		}
	},
	onLoad({ l }) {
		this.m_current = l;
		this.m_StateID = this.m_list[l].value;
	},

	setup() {
		const m_list = reactive([
			{
				name: '全部',
				value: -1
			},
			{
				name: '待付款',
				value: 0
			},
			{
				name: '待发货',
				value: 1
			},
			{
				name: '待收货',
				value: 2
			}
		]);
		const m_StateID = ref(-1);
		const m_PageIndex = ref(0);
		const m_PageSize = ref(10);
		const m_Total = ref(0);
		const m_show = ref(false);
		const m_current = ref(0);

		onMounted(async () => {
			if (!useUser().hasLogin) {
				uToast('您还未登录！', 'error');
				setTimeout(() => {
					uNavigateBack();
				}, 1500);
			} else {
				await GetOrderList(m_StateID.value);
			}
		});

		async function onTabClick(item) {
			console.log(item, 'item');
			m_current.value = item.index;
			if (m_StateID.value == item.value) {
				return;
			} else {
				m_PageIndex.value = 0;
				m_pageData.value = [];
				m_StateID.value = item.value;
				m_show.value = false;
				await GetOrderList();
			}
		}

		const m_pageData = ref([]);

		async function GetOrderList() {
			const { Data, Count } = await reqPost('GetOrderList', {
				strJson: JSON.stringify({
					StateID: m_StateID.value,
					PageIndex: m_PageIndex.value,
					// BgDate: "",
					// EnDate: "",
					GoodsID: -1,
					FBillType: -1
				})
			});
			m_pageData.value = [...m_pageData.value, ...Data];
			m_Total.value = Count;
			m_show.value = true;
		}

		function goShopping() {
			uSwitchTab('/pages/tab_bar/fl');
		}

		async function onBtnClick(key, order) {
			console.log('order :>> ', order);
			switch (key) {
				case 1: {
					console.log('取消订单');
					if (await uModal('确定要取消吗？')) {
						const { Message } = await reqPost('CancelOrder', {
							id: order.entryid
						});
						uToast(Message);
						setTimeout(async () => {
							m_pageData.value = [];
							m_PageIndex.value = 0;
							await GetOrderList();
						}, 1000);
					}
					break;
				}

				// 付款
				case 2: {
					const res = await reqPost('SetRenewalsPay', {
						openid: uGetStorageSync('userInfo').openId,
						total_fee: parseFloat(order.total).toFixed(2),
						years: 0,
						detaileds: JSON.stringify([
							{
								checked: true,
								FItemID: order.entryid, // 订单主表主键
								number: order.number // 本地订单号
							}
						])
					});
					const paySign = res.Data?.respData?.paySign;
					if (paySign) {
						await uni.requestPayment({
							provider: 'wxpay',
							timeStamp: res.Data?.respData?.payTimeStamp,
							nonceStr: res.Data?.respData?.paynonceStr,
							package: res.Data?.respData?.payPackage,
							signType: res.Data?.respData?.paySignType,
							paySign: paySign,
							success(res) {
								console.log('res :>> ', res);
								uni.redirectTo({
									url: '/pages/pay/pay_success/index?orderId=' + order.entryid
								});
							},
							fail() {
								uToast('支付失败~', 'error');
								setTimeout(() => {
									uRedirectTo('/pages/order/OrderList?l=0');
								}, 1500);
							}
						});
					}
					break;
				}

				case 3: {
					if (await uModal('确定要收货吗？')) {
						const { Message } = await reqPost('ConfirmReceipt', {
							orderId: order.entryid
						});
						uToast(Message);
						setTimeout(async () => {
							m_pageData.value = [];
							m_PageIndex.value = 0;
							await GetOrderList();
						}, 1000);
					}
					break;
				}

				default:
					break;
			}
		}

		function onOrderClick(order) {
			console.log('order :>> ', order);
			uNavigateTo('/pages/order/orderDetail?id=' + order.entryid);
		}

		return {
			m_list,
			onTabClick,
			m_pageData,
			m_show,
			goShopping,
			m_PageSize,
			m_Total,
			onBtnClick,
			onOrderClick,
			m_StateID,
			m_current
		};
	}
};
</script>

<style lang="scss" scoped>
@import './scss/OrderList.scss';

::v-deep .u-tabs__wrapper__nav__item {
	width: 25%;
	padding: 0 0 !important;
}
</style>
